package com.shop.loan.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

public class NumberToChinese {

    // 中文数字
    private static final List<String> CHINESE_NUMBERS = Arrays.asList(
            "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"
    );

    // 中文单位
    private static final List<String> CHINESE_UNITS = Arrays.asList(
            "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾",
            "佰", "仟", "兆", "拾", "佰", "仟"
    );

    // 小数部分单位
    private static final List<String> DECIMAL_UNITS = Arrays.asList("角", "分");

    // 最大支持的位数（防止溢出）
    private static final int MAX_SCALE = 16;

    /**
     * 将数字转换为中文大写金额
     * @param number 要转换的数字(支持String,Number类型)
     * @return 中文大写金额字符串
     */
    public static String toChineseUpper(Object number) {
        if (number == null) {
            return "零元整";
        }

        BigDecimal num;
        try {
            // 统一转换为BigDecimal
            if (number instanceof BigDecimal) {
                num = (BigDecimal) number;
            } else if (number instanceof String) {
                num = new BigDecimal(((String) number).trim());
            } else if (number instanceof Number) {
                num = new BigDecimal(number.toString());
            } else {
                throw new IllegalArgumentException("不支持的数据类型: " + number.getClass());
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的数字格式: " + number);
        }

        // 检查数字范围
        if (num.compareTo(BigDecimal.ZERO) == 0) {
            return "零元整";
        }

        // 处理负数
        boolean isNegative = num.compareTo(BigDecimal.ZERO) < 0;
        if (isNegative) {
            num = num.abs();
        }

        // 设置精度并四舍五入到分
        num = num.setScale(2, RoundingMode.HALF_UP);

        // 分离整数和小数部分
        BigDecimal[] parts = num.divideAndRemainder(BigDecimal.ONE);
        long integerPart = parts[0].longValue();
        int decimalPart = parts[1].movePointRight(2).intValue();

        // 处理整数部分
        String integerStr = convertIntegerPart(integerPart);

        // 处理小数部分
        String decimalStr = convertDecimalPart(decimalPart);

        // 拼接结果
        StringBuilder result = new StringBuilder();
        if (isNegative) {
            result.append("负");
        }
        result.append(integerStr);

        if (decimalStr.isEmpty()) {
            result.append("元整");
        } else {
            result.append("元").append(decimalStr);
        }

        return result.toString();
    }

    /**
     * 转换整数部分
     */
    private static String convertIntegerPart(long number) {
        if (number == 0) {
            return "零";
        }

        StringBuilder sb = new StringBuilder();
        int unitIndex = 0;
        boolean needZero = false;
        boolean hasUnit = false; // 标记是否已经有单位(万/亿/兆)

        while (number > 0) {
            int digit = (int) (number % 10);

            if (digit == 0) {
                if (needZero) {
                    needZero = false;
                    sb.insert(0, CHINESE_NUMBERS.get(0));
                }

                // 处理万、亿等单位
                if ((unitIndex == 4 || unitIndex == 8 || unitIndex == 12) && !hasUnit) {
                    sb.insert(0, CHINESE_UNITS.get(unitIndex));
                    hasUnit = true;
                }
            } else {
                if (hasUnit) {
                    hasUnit = false;
                }
                needZero = true;
                sb.insert(0, CHINESE_NUMBERS.get(digit) + CHINESE_UNITS.get(unitIndex));
            }

            number /= 10;
            unitIndex++;

            // 防止超出支持的最大位数
            if (unitIndex >= MAX_SCALE) {
                break;
            }
        }

        return sb.toString();
    }

    /**
     * 转换小数部分
     */
    private static String convertDecimalPart(int decimal) {
        if (decimal == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        int jiao = decimal / 10;  // 角
        int fen = decimal % 10;   // 分

        if (jiao > 0) {
            sb.append(CHINESE_NUMBERS.get(jiao)).append(DECIMAL_UNITS.get(0));
        }

        if (fen > 0) {
            sb.append(CHINESE_NUMBERS.get(fen)).append(DECIMAL_UNITS.get(1));
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        // 测试用例
        Object[] testCases = {
                0,
                123,
                1001,
                10001,
                100001,
                1000001,
                new BigDecimal("123456789.126"), // 测试四舍五入
                -1234.56,
                100000000,
                new BigDecimal("2003004005.785"), // 测试四舍五入
                "9999999999999.99", // 大数测试
                new BigDecimal("1234567890123456"), // 超大数测试
                "0.01",
                "0.10",
                "0.99",
                "1.00",
                "invalid" // 测试异常情况
        };

        for (Object num : testCases) {
            try {
                System.out.printf("%20s -> %s%n",
                        num.toString(),
                        toChineseUpper(num));
            } catch (Exception e) {
                System.out.printf("%20s -> 转换失败: %s%n", num, e.getMessage());
            }
        }
    }
}